<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="60%" @close="handleClose">
    <el-table
      ref="table"
      :data="inventoryList"
      border
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
    >
      <el-table-column 
        type="selection" 
        width="55" 
        align="center"
        :selectable="row => row.availableQty > 0" 
      />
      <el-table-column label="批次号" prop="batchNo" />
      <el-table-column label="仓库" prop="warehouseName" />
      <el-table-column label="库位" prop="locationName" />
      <el-table-column label="可用数量" prop="availableQty" />
      <el-table-column label="单位" prop="unit" />
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 导入批次库存查询API
import { getBatchStockByItemCode } from '@/api/ck/material';

export default {
  name: 'SelectBatchDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '选择库存批次'
    },
    materialId: {
      type: Number,
      default: null
    },
    materialCode: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      inventoryList: [],
      selectedBatches: []
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },
  watch: {
    visible(val) {
      if (val && this.materialCode) {
        this.getInventoryList();
      }
    }
  },
  methods: {
    getInventoryList() {
      if (!this.materialCode) {
        console.warn("物料编码为空，无法查询批次库存");
        return;
      }

      console.log("查询物料编码为 " + this.materialCode + " 的批次库存");
      getBatchStockByItemCode(this.materialCode).then(response => {
        if (response.code === 200 && response.data && response.data.batchStockList) {
          // 将后端返回的数据转换为前端需要的格式
          this.inventoryList = response.data.batchStockList.map(item => ({
            inventoryId: item.itemId, // 使用库存明细ID
            batchNo: item.batchCode,
            warehouseName: item.warehouseName,
            locationName: item.locationName + (item.areaName ? '-' + item.areaName : ''),
            availableQty: item.quantityNum,
            unit: item.unitName
          }));
        } else {
          this.inventoryList = [];
          this.$message.warning('未查询到该物料的批次库存信息');
        }
      }).catch(error => {
        console.error('查询批次库存失败:', error);
        this.inventoryList = [];
        this.$message.error('查询批次库存失败');
      });
    },
    handleSelectionChange(selection) {
      // Only allow single selection - if more than one is selected, keep only the latest one
      if (selection.length > 1) {
        const latestSelected = selection[selection.length - 1];
        this.$refs.table.clearSelection();
        this.$refs.table.toggleRowSelection(latestSelected, true);
        this.selectedBatches = [latestSelected];
      } else {
        this.selectedBatches = selection;
      }
    },
    handleConfirm() {
      if (this.selectedBatches.length === 0) {
        this.$modal.msgWarning("请选择一个批次");
        return;
      }
      this.$emit('confirm', this.selectedBatches);
      this.dialogVisible = false;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    tableRowClassName({ row }) {
      return row.availableQty <= 0 ? 'disabled-row' : '';
    }
  }
};
</script>

<style scoped>
.disabled-row {
  color: #C0C4CC;
  background-color: #F5F7FA;
  cursor: not-allowed;
}
</style> 